package com.assets.Fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.assets.Input.Rfid_Input;
import com.assets.newNHF.util.LogUtils;
import com.assets.util.MyOkHttp;
import com.assets.util.Since_case;
import com.assets.util.TrustAllCerts;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.assets.Adapter.Fragment_Adap;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.bean.Fragment2_bean;
import com.assets.menu.SlideSideMenuExampleActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lemonade.widgets.slidesidemenu.SlideSideMenuTransitionLayout;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by zq on 2017/1/13.
 */

public class Fragment2 extends Fragment {
    private ImageView imageView;
    private String url = "http://" + Url.IP + "/api/assetEntryQuery";
    private String up_url = "http://" + Url.IP + "/api/assetEntry";
    private SlideSideMenuExampleActivity activity;
    private String id;
    private List<String> check_id = new ArrayList<>();
    private List<Fragment2_bean> check = new ArrayList<>();
    private List<String> CheckdetailId = new ArrayList<>();
    private Button button1;
    private Handler handler = new Handler();
    private Button button2;
    private BaseAdapter adapter;
    private Button button3, button4;
    private ListView listView;

    public Fragment2() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_second2, null);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = (SlideSideMenuExampleActivity) getActivity();
        SharedPreferences mm = getActivity().getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id", "");
        init();
        load();
    }


    private void init() {
        button4 = (Button) activity.findViewById(R.id.button4);
        button1 = (Button) activity.findViewById(R.id.button1);
        button2 = (Button) activity.findViewById(R.id.button2);
        listView = (ListView) activity.findViewById(R.id.listveiw);
        button3 = (Button) activity.findViewById(R.id.button3);
        imageView = (ImageView) getActivity().findViewById(R.id.opmenu);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SlideSideMenuTransitionLayout mSlideSideMenu = (SlideSideMenuTransitionLayout) getActivity().findViewById(R.id.slide_side_menu);
                mSlideSideMenu.toggle();
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (CheckdetailId.size() > 0) {
                    new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, activity, AlertView.Style.Alert, new OnItemClickListener() {
                        @Override
                        public void onItemClick(Object o, int position) {
                            //取消：position=-1,确定 position=0
                            if (position == 0) {

                                up_load();
                            }
                            if (position == -1) {

                            }

                        }
                    }).setCancelable(true).setOnDismissListener(activity).show();
                } else Toast.makeText(activity, "请选择需要入库的资产类型", Toast.LENGTH_LONG).show();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fragment_Adap.ViewHolder viewHolder = (Fragment_Adap.ViewHolder) view.getTag();
                viewHolder.checkBox.toggle();
                check.get(position).setIscheck(viewHolder.checkBox.isChecked());

                if (viewHolder.checkBox.isChecked() == true) {
                    CheckdetailId.add(check_id.get(position));
                } else {
                    CheckdetailId.remove(check_id.get(position));
                }
                // 用TextView显示
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CheckdetailId.clear();
                for (int i = 0; i < check.size(); i++) {
                    // 改值
                    if (check.get(i).ischeck()) {
                        check.get(i).setIscheck(false);
                    } else {
                        check.get(i).setIscheck(true);
                    }
                    // 刷新
                    adapter.notifyDataSetChanged();
                    // 如果为选中
                    if (check.get(i).ischeck()) {
                        CheckdetailId.add(check_id.get(i));

                    } else CheckdetailId.remove(check_id.get(i));
                }
            }
        });
        button4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(activity, Rfid_Input.class);
                startActivity(intent);
            }
        });
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int j = 0;
                for (int i = 0; i < check.size(); i++) {
                    if (check.get(i).ischeck()) {
                        j++;
                    }
                }

                if (j < check.size()) {
                    CheckdetailId.clear();
                    for (int i = 0; i < check.size(); i++) {
                        // 改变boolean
                        check.get(i).setIscheck(true);
                        // 如果为选中
                        if (check.get(i).ischeck()) {
                            CheckdetailId.add(check_id.get(i));
                        }
                    }
                    // 刷新
                    adapter.notifyDataSetChanged();
                    // 显示
                } else {
                    for (int i = 0; i < check.size(); i++) {
                        // 改变boolean
                        check.get(i).setIscheck(false);
                        // 如果为选中
                        if (!check.get(i).ischeck()) {
                            CheckdetailId.remove(check_id.get(i));
                        }
                    }
                    // 刷新
                    adapter.notifyDataSetChanged();
                    // 显示
                }

            }
        });


    }

    private void up_load() {
        new Thread(() -> {
            OkHttpClient client =new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();//创建OkHttpClient对象。
            FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
            formBody.add("userId", Since_case.getInstance().getUserId())
                    .add("names", CheckdetailId.toString()); //传递键值对参数
            final Request request = new Request.Builder()//创建Request 对象。
                    .url(up_url)
                    .post(formBody.build())//传递请求体
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    //回调方法的使用与get异步请求相同
                    activity.showToast("请连接网络后重试");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String responseData = response.body().string();
                    LogUtils.d(responseData);
                    try {
                        JSONObject jsonObject = new JSONObject(responseData);
                        if (jsonObject.getString("state").equals("1")) {
                            check.clear();
                            check_id.clear();
                            CheckdetailId.clear();
                            activity.runOnUiThread(() -> {
                                adapter.notifyDataSetChanged();
                                load();
                                Toast.makeText(activity, "上传成功", Toast.LENGTH_LONG).show();
                            });
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }).start();
    }


    private void load() {
        Map<String, String> map = new HashMap<>();
        map.put("userId", Since_case.getInstance().getUserId());
        MyOkHttp.getInstance().post(url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                activity.showToast("请连接网络后重试");
            }

            @Override
            public void requestComplete() {

            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                final String responseData = response.body().string();
                LogUtils.d(responseData);
                check.clear();
                check_id.clear();
                CheckdetailId.clear();
                Gson gson = new Gson();
                List<Fragment2_bean> userList = gson.fromJson(responseData, new TypeToken<List<Fragment2_bean>>() {
                }.getType());
                for (int i = 0; i < userList.size(); i++) {
                    check.add(new Fragment2_bean(false, userList.get(i).getName(), userList.get(i).getNum()));
                    check_id.add(userList.get(i).getName());
                }
                activity.runOnUiThread(() -> {
                    adapter = new Fragment_Adap(check, activity);
                    listView.setAdapter(adapter);
                });
            }
        });
    }

    @Override
    public void onStart() {
        Timer timer = new Timer();//实例化Timer类
        timer.schedule(new TimerTask() {
            public void run() {
                Log.i("ooooooooooo", "3");
                load();
                this.cancel();
            }
        }, 200);//五百毫秒
        super.onStart();
    }

}
